<template>
    <div class="common-layout">

        <!-- 面包屑 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>
                <a href="/">网格管理</a>
            </el-breadcrumb-item>
            <el-breadcrumb-item>物理网格</el-breadcrumb-item>
        </el-breadcrumb>



        <el-container style="margin-top: 20px;">
            <el-aside width="242px" style="margin-top:20px;">
                <!-- {{ areaInfo }}{{ tableData }} -->
                <!-- 放树形的地方 -->
                <el-input v-model="filterText" style="width: 240px" placeholder="查询关键字" />

                <el-tree ref="treeRef" style="max-width: 600px" class="filter-tree" :data="data" :props="defaultProps"
                    default-expand-all :filter-node-method="filterNode" @node-click="nodeClicked" />

            </el-aside>
            <el-main>
                <div style="border: 1px solid black; padding: 15px;">
                    <!-- 查询区域 -->
                    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                        <el-form-item label="网格名称">
                            <el-input v-model="searchForm.girdName" placeholder="请输入网格名称" clearable />
                        </el-form-item>
                        <el-form-item label="区域名称">
                            <el-input v-model="searchForm.areaName" placeholder="请输入区域名称" clearable />
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="search">搜索</el-button>
                        </el-form-item>
                    </el-form>

                </div>

                <!-- 表格区域 -->
                <div style="border: 1px solid black; padding: 15px;margin-top: 15px;">
                    <!-- {{ page }} -->
                    <el-button type="success" @click="toAdd()">
                        添加
                    </el-button>
                    <el-table :data="tableData" style="width: 100%">
                        <el-table-column type="index" label="序号" width="120" />
                        <el-table-column prop="gridCode" label="网格编码" width="120" />
                        <el-table-column prop="girdName" label="网格名称" width="120" />
                        <el-table-column prop="areaName" label="区域名称" width="600" />
                        <el-table-column fixed="right" label="操作" min-width="140">
                            <template #default="scope">
                                <el-button type="danger" size="small" @click="del(scope.row)">
                                    删除
                                </el-button>
                                <el-button type="primary" size="small" @click="update(scope.row)">编辑</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                        :page-sizes="[2, 3, 4, 5]" :size="page.totalCount" :background="true"
                        layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount" />
                </div>
            </el-main>
        </el-container>
    </div>


    <!-- 添加弹窗 -->

    <el-dialog v-model="dialogTableVisible" title="添加弹窗" width="800">
        <!-- 弹窗里放表单 -->

        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="所属区域" prop="areaName">
                <el-input v-model="ruleForm.areaName" disabled />
            </el-form-item>
            <el-form-item label="网格编码" prop="gridCode">
                <el-input v-model="ruleForm.gridCode" />
            </el-form-item>
            <el-form-item label="网格名称" prop="girdName">
                <el-input v-model="ruleForm.girdName" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    添加
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="updateTableVisible" :title='"更新" + ruleForm.girdName' width="800">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="所属区域" prop="areaName">
                <el-input v-model="ruleForm.areaName" disabled />
            </el-form-item>
            <el-form-item label="网格编码" prop="gridCode">
                <el-input v-model="ruleForm.gridCode" />
            </el-form-item>
            <el-form-item label="网格名称" prop="girdName">
                <el-input v-model="ruleForm.girdName" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="updateForm(ruleFormRef)">
                    编辑
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>


</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { tr } from 'element-plus/es/locales.mjs';


//删除逻辑
const del = (row: any) => {

    ElMessageBox.confirm(
        '您确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            //调用删除接口
            axios.put('http://localhost:5253/api/Physical/DelPhysicalGrid', row).then(res => {
                if (res.data.data > 0) {

                    search();//刷新数据
                    ElMessage({
                        type: 'success',
                        message: res.data.msg,
                    })

                } else {
                    ElMessage.error(res.data.msg);
                }
            });


        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除失败',
            })
        })
}



//编辑逻辑

//先把行数据赋值给双向绑定的表单 ruleForm, 打开弹窗
const update = (row: any) => {
    console.log(row);

    ruleForm.girdName = row.girdName
    ruleForm.gridCode = row.gridCode
    ruleForm.areaId = row.areaId
    ruleForm.areaName = row.areaName
    ruleForm.id = row.id



    updateTableVisible.value = true;//打开弹窗
}


const updateForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {//验证通过后,提交表单

            axios.put('http://localhost:5253/api/Physical/UpdatePhsicalGrid', ruleForm).then(res => {

                if (res.data.data > 0) {

                    ElMessage.success(res.data.msg);
                    search();//刷新数据
                    updateTableVisible.value = false;//关闭弹窗

                } else {
                    ElMessage.error(res.data.msg);
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}


const updateTableVisible = ref(false)

// 添加逻辑
const dialogTableVisible = ref(false)
const toAdd = () => {
    if (areaInfo.areaName == "") {
        ElMessageBox.alert("请您先选择所属区域");
        search();
    } else {
        dialogTableVisible.value = true;
    }


}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    girdName: '',
    gridCode: '',
    areaName: '',
    areaId: 0,
    id: 0

})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    girdName: [
        { required: true, message: '请输入网格名称', trigger: 'blur' },
        { min: 3, max: 15, message: '网格名称的长度应该为3-15位', trigger: 'blur' },
    ],
    gridCode: [
        { required: true, message: '请输入网格编码', trigger: 'blur' },
        { min: 3, max: 15, message: '网格编码的长度应该为3-15位', trigger: 'blur' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {//验证通过后,提交表单

            axios.post('http://localhost:5253/api/Physical/CreatePhysicalGrid', ruleForm).then(res => {

                if (res.data.data > 0) {

                    ElMessage.success(res.data.msg);

                } else {
                    ElMessage.error(res.data.msg);
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

const searchForm = reactive({
    girdName: '',
    areaName: ''
})



const page = reactive({
    PageSize: 5,
    PageIndex: 1,
    totalCount: 0,
    totalPage: 0
})
watch(page, () => {
    search();
})

const search = () => {//搜索方法
    axios.get('http://localhost:5111/api/Physical/GetPhysicalGrid', {
        params: {
            AreaName: searchForm.areaName,
            GirdName: searchForm.girdName,
            PageSize: page.PageSize,
            PageIndex: page.PageIndex
        }
    }).then(res => {
        tableData.value = res.data.items
        page.totalCount = res.data.totalCount;
        page.totalPage = res.data.totalPage;

    })
}

const tableData = ref([]) //用来绑定给表格的数据





interface Tree {
    [key: string]: any
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
    children: 'children',
    label: 'areaName',
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.areaName.includes(value)
}

const data = ref([])
const setTreeData = () => {
    axios.get('http://localhost:5015/api/Area/GetAreaTree').then(res => {
        data.value = res.data.data
    });
}

//用来保存选择的区域信息
const areaInfo = reactive({
    id: 0,
    areaName: ''
})

const nodeClicked = (x: any, y: any, z: any, w: any) => {
    areaInfo.id = x.id;
    areaInfo.areaName = x.areaName

    ruleForm.areaName = x.areaName
    ruleForm.areaId = x.id

}

onMounted(() => {
    setTreeData();
    search();
});
</script>